import {useState, ChangeEvent} from 'react';
import TutorialData from '../types/Tutorial';
import TutorialService from '../services/TutorialService';

const AddTutorial = () =>{
    const initTutorial = {
        id:0,
        title:"",
        description:""
    }

    const [tutorial,setTutorial] = useState<TutorialData>(initTutorial);
    const [submitted, setSubmitted] = useState<boolean>(false);

    const newTutorial = ()=> {
        setTutorial(initTutorial);
        setSubmitted(false);
    }

    const handleInputChange = (e: ChangeEvent<HTMLInputElement>)=>{
        const {name, value}= e.target;
        setTutorial({...tutorial, [name]:value});
    }

    const createTutorial = async ()=>{
        var data ={
            id:0,
            title: tutorial.title,
            description:tutorial.description
        }
        const response = await TutorialService.create(data);
        setTutorial({
            id:response.data.id,
            title:response.data.title,
            description:response.data.description
        });
        setSubmitted(true);
        console.log(response.data);
    }

    return (
        <div className="submit-form">
            {submitted ? (
                <div>
                    <h4>You submitted successfully!</h4>
                    <button className="btn btn-success" onClick={newTutorial}>
                        Add
                    </button>
                </div>
            ):(
                <div>
                    <div className="form-group">
                        <label htmlFor="title">Title</label>
                        <input type="text" 
                            id="title" 
                            name="title"
                            className="form-control"
                            required
                            value={tutorial.title}
                            onChange={handleInputChange}
                            />
                    </div>
                    <div className="form-group">
                        <label htmlFor="description">Description:</label>
                        <input type="text"
                                id="description"
                                name="description"
                                className="form-control"
                                required
                                value={tutorial.description}
                                onChange= {handleInputChange}
                        />
                    </div>
                    <button onClick={createTutorial} className="btn btn-success">
                        Submit
                    </button>
                </div>
            )}
        </div>
    )
}

export default AddTutorial;